package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    @Autowired
    private UserFreezeService userFreezeService;

    /**
     * 生成验证码
     * @param phone
     */
    public void SendMsg(String phone) {
        //根据手机号查询用户，如果用户存在，判断是否被冻结
        User user = userApi.findByMobile(phone);
        if(user != null) {
            userFreezeService.checkUserStatus("1",user.getId());
        }
        //1，随机生成6为随机数
        //String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        //2,调用SmsTemplate短信模板类发送验证码
        //smsTemplate.SendSms(phone, code);
        //3,把验证码存到redis中,过期时间5分钟
        redisTemplate.opsForValue().set("iphone" + phone, code, Duration.ofMinutes(20));
    }

    /**
     * 登录校验
     * @param phone
     * @param code
     * @return
     */
    public Map loginVerification(String phone, String code) {
        //1，从redis中获取验证验证码
        String redisCode = redisTemplate.opsForValue().get("iphone" + phone);
        //2，验证码校验 如果验证码是空或者不一样就抛异常
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //验证码无效
            throw new BusinessException(ErrorResult.loginError());
        }
        //3，删除redis中的数据
        redisTemplate.delete("iphone" + phone);
        //4，通过手机号码查询用户
        //标记 isNew
        User user = userApi.findByMobile(phone);
        boolean isNew = false;
        //代表登录
        String type = "0101";
        //5，如果用户不存在就添加数据到数据库中
        if (user == null) {
            //代表注册
            type = "0102";
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true; //如果是新用户修改标记为true

            //注册环信用户
            String hxUser = "hx" + user.getId();
            Boolean aBoolean = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if (aBoolean) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.updateHunXin(user);
            }
        }
        //调用工具类完成日志消息发送
        mqMessageService.sendLogService(user.getId(), type, "user", null);

        //6，生成token 传入id和手机号
        Map mapToken = new HashMap();
        mapToken.put("id", user.getId());
        mapToken.put("mobile", phone);
        String token = JwtUtils.getToken(mapToken);
        //7，构造返回值
        Map retMap = new HashMap();
        retMap.put("token", token);
        retMap.put("isNew", isNew);
        return retMap;
    }

    /**
     * 修改手机号的校验验证码
     * @param mobile
     * @param verificationCode
     * @return
     */
    public Boolean checkVerificationCode(String mobile, String verificationCode) {
        //1，从redis中获取验证验证码
        String redisCode = redisTemplate.opsForValue().get("iphone" + mobile);
        //2，验证码校验 如果验证码是空或者不一样就抛异常
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(verificationCode)) {
            //验证码无效 返回false
            return false;
        }
        //3，删除redis中的数据
        redisTemplate.delete("iphone" + mobile);
        return true;
    }

    /**
     * 修改手机号
     * @param phone
     */
    public void phone(String phone) {
        //通过当前登录手机号获取对象
        User user = userApi.findByMobile(UserHolder.getMobile());
        //修改对象的手机号
        user.setMobile(phone);
        //调用api修改数据
        userApi.update(user);

    }
}
